package com.example.sudoku;

import android.content.Context;
import java.io.File;
import java.util.Arrays;
import java.util.regex.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileOutputStream;

// 用于保存历史排行榜
public class save {
    private static Context context;

    // 使用前由MainActivity调用初始化
    public static void setContext(Context mContext){
        context = mContext;
    }

    // 清除历史记录
    public static void clearFile() {
        File file = new File(context.getFilesDir(), "test.txt");
        try {
            if (file.exists()) {
                FileOutputStream outputStream = context.openFileOutput("test.txt", Context.MODE_PRIVATE);
                outputStream.write("".getBytes());
                outputStream.flush();
                outputStream.close();
            }
        } catch (Exception e) {
            //
        }
    }

    // 返回较大值
    public static int maxnum(int a,int b)
    {
        if( a > b) return a;
        return b;
    }

    // 计算分数
    public static int return_score(int time, int mode,int flag) {
        if (mode == 0&&flag==0) {//easy
            return  maxnum(99-time,60);
        }
        if (mode == 1&&flag==0) {//normal
            return maxnum(99-time/5,60);
        }
        if (mode == 2&&flag==0) {//difficult
            return maxnum(99-time/9,60);
        }
        if (mode == 3&&flag==0) {//very difficult
            return maxnum(99-time/15,60);
        }
        if (mode == 0&&flag==1) {//easy
            return  maxnum(99-time*2,60);
        }
        if (mode == 1&&flag==1) {//normal
            return maxnum(99-time*2/5,60);
        }
        if (mode == 2&&flag==1) {//difficult
            return maxnum(99-time*2/9,60);
        }
        if (mode == 3&&flag==1) {//very difficult
            return maxnum(99-time*2/15,60);
        }
        return 0;
    }

    // 利用正则表达式获得字符串中的分数
    public static String reg_score(String data) {
        String s = "1";

        Pattern pattern = Pattern.compile("[a-zA-Z]{5}:[0-9]{2}");
        Matcher matcher = pattern.matcher(data);
        if (matcher.find()) {
            String t = matcher.group(0);
            pattern = Pattern.compile("[0-9]{2}");
            matcher = pattern.matcher(t);
            if (matcher.find())
                return matcher.group(0);
        } else {
            System.out.println("nothing");
            return s;
        }
        return s;
    }

    //非覆盖保存，新增字符串加在最后
    public static void save_file(int time, int mode, int flag) {
        int score = return_score(time, mode,flag);
        FileOutputStream o = null;
        byte[] buff = new byte[]{};
        String a = "";
        if (score >= 10)
            // 后续采用正则表达式寻找score,为保持格式一致，分数限定为两位
            a = "t:" + Integer.toString(time) + "s " + "mode:" + Integer.toString(mode) + " score:" + Integer.toString(score)+" flag:"+Integer.toString(flag);
        else
            a = "t:" + Integer.toString(time) + "s " + "mode:" + Integer.toString(mode) + " score:0" + Integer.toString(score)+" flag:"+Integer.toString(flag);
        File file = new File(context.getFilesDir(), "test.txt");
//        file.delete();
        try {
            // 打开文件流
            FileOutputStream outputStream = context.openFileOutput("test.txt", Context.MODE_APPEND);
            // 写入数据
            outputStream.write(a.getBytes());
            outputStream.write('\n');
            outputStream.flush();
            outputStream.close();
            score_sort();
        } catch (Exception e) {
            //
        }
    }

    //覆盖保存
    public static void save_file1(String a) {
        FileOutputStream o = null;
        byte[] buff = new byte[]{};
        try {
            File file = new File(context.getFilesDir(), "test.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            buff = a.getBytes();
            o = new FileOutputStream(file,false);
            o.write(buff);
            o.write('\n');
            o.flush();
            o.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void save_file2(String a) {
        FileOutputStream o = null;
        byte[] buff = new byte[]{};
        try {
            File file = new File(context.getFilesDir(), "test.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            buff = a.getBytes();
            o = new FileOutputStream(file, true);
            o.write(buff);
            o.write('\n');
            o.flush();
            o.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 返回文件中的字符串
    public static String [] return_paihangbang() {
        File file = new File(context.getFilesDir(), "test.txt");
        BufferedReader reader = null;
        String s [] = new String[10];
        Arrays.fill(s, "");
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = "";
            int line = 0;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 获取文件存储的字符串
                s[line] = tempString;
                line++;
                if(line > 9) break;
            }
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {

                }
            }
        }
        Arrays.fill(s, "");
        return s;
    }

    // 按照分数进行排序
    public static void score_sort() {
        String result = "";
        File file = new File(context.getFilesDir(), "test.txt");
        BufferedReader reader = null;
        String s[]=new String[100];
        String score[]=new String[100];
        int score1[]=new int[100];
        Arrays.fill(score1,0);
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = "";
            int line = 0;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
//                System.out.println("line " + line + ": " + tempString);
                s[line]=tempString;
                score[line]=reg_score(tempString);
                score1[line]=Integer.parseInt(score[line]);
//                System.out.println(score1[line]);
                line++;
            }
            line--;
            String ss="";
//            System.out.println(line);
            if(line<10) {
                int ans=-1;
                for (int i = 0; i < line; i++) {
                    if (score1[i] <= score1[line]) {
                        ans=i;
                        break;
                    }
                }
                if(ans==-1) ;
                else {
                    if (ans == 0){
                        save_file1(s[line]);
                        for (int i = 0; i < line; i++)
                            save_file2(s[i]);
                    }
                    else{
                        save_file1(s[0]);
                        for (int i = 1; i < line; i++) {
                            if(ans==i) save_file2(s[line]);
                            save_file2(s[i]);
                        }
                    }
                }
            }
            else {
                int ans=-1;
                for (int i = 0; i < line; i++) {
                    if (score1[i] <= score1[line]) {
                        ans=i;
                        break;
                    }
                }
//                System.out.println(ans);
                if(ans==-1) {
                    save_file1(s[0]);
                    for (int i = 1; i < line; i++) {
                        save_file2(s[i]);
                    }
                }
                else {
                    if (ans == 0){
                        save_file1(s[line]);
                        for (int i = 0; i < line-1; i++)
                            save_file2(s[i]);
                    }
                    else{
                        save_file1(s[0]);
                        for (int i = 1; i < line-1; i++) {
                            if(ans==i) save_file2(s[line]);
                            save_file2(s[i]);
                        }
                    }
                }


            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                }
                catch (IOException e1) {
                }
            }
        }
    }
}
